import ResizableTable from '@/components/ResizableTable/ResizableTable';
import {
  CustomerCreate,
  CustomerDelete,
  CustomerList,
  CustomerUpdate,
} from '@/services/customer';
import { BetaSchemaForm } from '@ant-design/pro-components';

import { tableSorter } from '@/utils';
import { UserOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
} from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { useUrlSearchParams } from '@umijs/use-params';
import { Avatar, Button, Card, Form, Input, Space, message } from 'antd';
import React, { Key, useEffect, useRef, useState } from 'react';
import { CreateColumns, UpdateColumns } from './Schema';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await CustomerCreate({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在更新');
  try {
    await CustomerUpdate({ ...fields });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

const upgradeForm = async (row: any) => {
  if (row.id) {
    return await handleUpdate(row);
  }
  return await handleAdd(row);
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (ids: any[]) => {
  const hide = message.loading('正在删除');
  if (ids.length === 0) return true;
  try {
    await CustomerDelete({
      ids,
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const CustomerPage: React.FC<unknown> = () => {
  const access = useAccess();
  const [params, setParams] = useUrlSearchParams({});
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalForm] = Form.useForm();
  const [row, setRow] = useState<any>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    form.setFieldsValue(params);
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '会员ID',
      dataIndex: 'id',
      width: 80,
      sorter: true,
    },
    {
      title: '头像',
      width: 50,
      dataIndex: 'avatar',
      render: (text: any) => (
        <Avatar
          shape="circle"
          style={{ margin: '0 10px' }}
          src={text}
          size={30}
          icon={<UserOutlined />}
        />
      ),
    },
    {
      title: '会员名',
      dataIndex: 'name',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
    },
    {
      title: '黑名单',
      dataIndex: 'is_active',
      render: (text: any) => (text ? '是' : '否'),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_: any, record: any) => (
        <>
          {access['biz.customer.update'] && (
            <Button
              type="link"
              onClick={() => {
                modalForm.setFieldsValue(record);
                setRow(record);
                setOpen(true);
              }}
            >
              更新
            </Button>
          )}
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card
        title={
          <div style={{ padding: '10px 0' }}>
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  modalForm.resetFields();
                  setRow(undefined);
                  setOpen(true);
                }}
              >
                新增
              </Button>
              {selectedRowKeys.length > 0 && (
                <Button
                  type="primary"
                  danger
                  onClick={async () => {
                    await handleRemove(selectedRowKeys);
                    actionRef.current?.reload();
                  }}
                >
                  删除
                </Button>
              )}
            </Space>
          </div>
        }
      >
        <div style={{ paddingBottom: 10 }}>
          <Space>
            <Form layout="inline" form={form}>
              <Form.Item name="phone" label="联系电话">
                <Input placeholder="请输入联系电话" />
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  onClick={() => {
                    actionRef.current?.reloadAndRest?.();
                  }}
                >
                  查询
                </Button>
              </Form.Item>
            </Form>
          </Space>
        </div>
        <ResizableTable
          actionRef={actionRef}
          rowKey="id"
          search={false}
          request={async (page: any, sort: any) => {
            const sorter = tableSorter(sort);
            const f = form.getFieldsValue();
            const p = {
              ...page,
              ...f,
              sorter: sorter ? sorter : params.sorter,
            };
            setParams(p);
            const { data, success, total } = await CustomerList(p);
            return {
              data: data || [],
              total,
              success,
            };
          }}
          // @ts-ignore
          columns={columns}
          rowSelection={{
            selectedRowKeys,
            onChange: (newSelectedRowKeys: React.Key[]) => {
              // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
              setSelectedRowKeys(newSelectedRowKeys);
            },
          }}
          pagination={{
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            current: Number(params.current),
            pageSize: Number(params.pageSize),
          }}
        />
      </Card>
      <BetaSchemaForm
        title={row?.id ? '编辑' : '新增'}
        columns={row?.id ? UpdateColumns : CreateColumns}
        form={modalForm}
        open={open}
        onOpenChange={setOpen}
        layoutType={'ModalForm'}
        onFinish={async (values: any) => {
          const is_ok = await upgradeForm({ ...row, ...values });
          if (is_ok) {
            actionRef.current?.reload();
            setOpen(false);
          }
        }}
      />
    </PageContainer>
  );
};

export default CustomerPage;
